import Toast from '../../../../miniprogram_npm/@vant/weapp/toast/toast';
const { IMOU_APPID, IMOU_APPSECRET } = require('../../../../utils/storage');
const $api = require('../../../../request/api').API;
const app = getApp();
Page({
  data: {
    cameraList: []
  },
  onLoad: function ({ businessId }) {
    $api.listCameraByBusiness({ businessId }).then(res => {
      const cameraList = res.data.data;
      if (cameraList && cameraList.length === 1 && cameraList[0].equipState < 3) {
        this.handleGotoCamera({
          currentTarget: { dataset: { equipmac: cameraList[0].equipMac, equipstate: cameraList[0].equipState } }
        });
        this.setData({ cameraList });
      } else {
        this.setData({ cameraList });
      }
    });
  },

  // 前往摄像头界面
  async handleGotoCamera(e) {
    const { equipmac, equipstate } = e.currentTarget.dataset;
    if (equipstate === 3) {
      Toast.fail('当前视频已离线');
      return;
    }
    const params = {
      appId: IMOU_APPID,
      appSecret: IMOU_APPSECRET
    };
    Toast.loading('数据加载中');
    const { result } = await $api.getImouToken(params);
    if (!result) {
      Toast.fail('获取设备token失败');
      Toast.clear();
      return;
    }
    app.globalData.IMOU_TOKEN = result.data.accessToken;
    Toast.clear();
    const channelListResult = await $api.listDeviceDetailsByIds({
      deviceList: [{ deviceId: equipmac }],
      token: result.data.accessToken
    });
    const deviceInfo = (channelListResult.result.data?.deviceList || [])[0];
    if (!deviceInfo) {
      Toast.fail('没有找到该设备的监控视频流');
      return;
    }
    const channelList = deviceInfo.channelList || [];
    channelList.forEach(item => {
      const { lastOffLineTime } = item;
      const year = lastOffLineTime.slice(0, 4);
      const month = lastOffLineTime.slice(4, 6);
      const day = lastOffLineTime.slice(6, 8);
      const hours = lastOffLineTime.slice(9, 11);
      const minutes = lastOffLineTime.slice(11, 13);
      const seconds = lastOffLineTime.slice(13, 15);
      item.lastOffLineTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    });
    if (channelList.length === 0) {
      Toast.fail('该设备没有视频通道');
      return;
    }
    if (channelList.length === 1) {
      wx.navigateTo({
        url: `/subcontract/equipment/pages/camera/index?deviceinfo=${equipmac}_${channelList[0].channelId}_${channelList[0].channelAbility}_${channelList[0].channelStatus}_${channelList[0].catalog}`
      });
    } else {
      wx.navigateTo({
        url: '/subcontract/equipment/pages/cameraChannelList/index?deviceId=' + equipmac
      });
    }
  }
});
